<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import type { ApiSysEmailSendConfigInput, ApiSysEmailSendConfigOut, ApiSysEmailSendTemplateInput, ApiUserInput, ApiUserOut } from '@/api-services';
import { UserApi } from '@/api-services/apis/user-api';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { REG_PWD, REG_USER_NAME } from '@/constants/reg';
import { ApiroleserviceApi } from '@/api-services/apis/apiroleservice-api';
import { SysemailsendtemplateApi } from '@/api-services/apis/sysemailsendtemplate-api';


defineOptions({
  name: 'EmailConfigOperateModal'
});

interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  rowData?: ApiSysEmailSendConfigOut | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation} = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    //添加邮件模板
    add: $t('page.emailManage.emailTemplate.form.addTitle'),
    //编辑邮件模板
    edit: $t('page.emailManage.emailTemplate.form.editTitle')
  };
  return titles[props.operateType];
});

// const regs: Record<UI.TableOperateType, App.Global.FormRule> = {
//   edit: { required: false },
//   add: {
//     required: true,
//     pattern: REG_PWD,
//     message: $t('form.pwd.invalid'),
//     trigger: 'change'
//   }
// };

// type Model = NonNullable<Pick<
//   ApiUserOut,
//   'account' | 'nick' | 'phone' | 'email' | 'isEnable'
// >>;
type Model = {
  [K in keyof Pick<ApiSysEmailSendTemplateInput,
    'id' | 'code' | 'title' | 'sourceType' | 'templateType' | 'isEnable' | 'isVerCode' | 'content' | 'dataId'>]: NonNullable<
      ApiSysEmailSendTemplateInput[K]
    >;
};
const model = ref(createDefaultModel());
// string转换为number
// model.value.roleIds = model.value.roleIdStr?.split(',').map(Number);
function createDefaultModel(): Model {
  return {
    id: 0,
    code: '',
    sourceType: 0,
    templateType: 1001,
    title: '',
    isEnable: true,
    isVerCode: false,
    content: '',
    dataId: 0
  };
}


function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  if (props.operateType === 'add') {
    const [err, res] = await feature(getAPI(SysemailsendtemplateApi).insert(model.value));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.addSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  } else {
    const [err, res] = await feature(getAPI(SysemailsendtemplateApi).update(model.value));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.updateSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  }

}
type RuleKey = Extract<keyof Model, 'code' | 'title'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  code: defaultRequiredRule,
  title: defaultRequiredRule
};

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>

<template>
  <NModal :align-center="true" v-model:open="visible" :title="title" :show-full-screen="true"  width="1000px">
    <ElForm ref="formRef" :model="model" :rules="rules"
     label-width="auto">
      <ElRow :gutter="16">
        <ElCol :lg="12" :xs="24">
          <!-- 唯一编号 -->
          <ElFormItem :label="$t('page.emailManage.emailTemplate.code')" name="code">
            <ElInput v-model="model.code" :placeholder="$t('page.emailManage.emailTemplate.form.code')" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <!-- 邮件标题 -->
          <ElFormItem :label="$t('page.emailManage.emailTemplate.title')" name="title">
            <ElInput v-model="model.title" :placeholder="$t('page.emailManage.emailTemplate.form.title')" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <!-- 来源类型 -->
          <ElFormItem :label="$t('page.emailManage.emailTemplate.sourceType')" name="sourceType">
            <ElSelect v-model="model.sourceType">
              <ElOption :value="0" :label="$t('page.emailManage.emailTemplate.sourceTypeEnum.system')" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.emailManage.emailTemplate.templateType')" name="templateType">
            <ElSelect v-model="model.templateType">
              <ElOption :value="0" :label="$t('page.emailManage.emailTemplate.form.templateTypeEnum.placeholder')"/>
              <ElOption :value="1001" :label="$t('page.emailManage.emailTemplate.templateTypeEnum.register')" />
              <ElOption :value="1002" :label="$t('page.emailManage.emailTemplate.templateTypeEnum.updatePwd')"/>
              <ElOption :value="1003" :label=" $t('page.emailManage.emailTemplate.templateTypeEnum.updateEmail')"/>
                <!-- 会员修改邮箱 -->
              <ElOption :value="1004" :label="$t('page.emailManage.emailTemplate.templateTypeEnum.resetPwd')"/>
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.manage.common.isEnable')" name="isEnable">
            <ElSwitch v-model="model.isEnable" />
          </ElFormItem>
        </ElCol>

        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.emailManage.emailTemplate.isVerCode')" name="isVerCode">
            <ElSwitch v-model:model-value="model.isVerCode" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="24" :xs="24">
          <NEditor v-model="model.content"></NEditor>
        </ElCol>
      </ElRow>
    </ElForm>
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style></style>
